package net.easyjava.framework.log;

import com.alibaba.fastjson.JSONObject;
import net.easyjava.framework.web.security.UserSecurityBean;
import net.easyjava.tools.date.DateConstants;
import net.easyjava.tools.date.DateTools;
import net.easyjava.tools.io.file.FileTools;
import net.easyjava.tools.http.request.RequestTools;
import net.easyjava.tools.model.ModelBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * Created by wxnacy on 16/3/20.
 */
public class LogUtils {
    private static Logger logger = LoggerFactory.getLogger(LogUtils.class);

    /**
     * controller层日志记录开始
     * @param request
     */
    public static void logAspectControllerBegin(HttpServletRequest request){
        String url = RequestTools.getRealUrl(request);
        logger.info("{}\tbegin---------------------", new Object[]{url});
        logger.info("{}\tparams[{}]", new Object[]{url,RequestTools.getParams(request)});
        logger.info("{}\theads[{}]",url,RequestTools.getHeads(request));
    }
    /**
     * controller层日志记录结束
     * @param request
     */
    public static void logAspectControllerEnd(HttpServletRequest request){
        String url = RequestTools.getRealUrl(request);
        logger.info("{}\tend-----------------------", new Object[]{url});
    }

    /**
     * 记录接口返回数据
     * @param request
     * @param modelBean
     */
    public static void logApiDetail(ModelBean modelBean,UserSecurityBean userSecurityBean ,HttpServletRequest request,HttpServletResponse response){
        long begin = System.currentTimeMillis();
        String url = RequestTools.getRealUrl(request);
        Map<String,String> params = RequestTools.getParams(request);
        Map<String,String> headers = RequestTools.getHeads(request);
//        System.out.println("request = " + request.getRequestedSessionId());

        StringBuffer fileName = new StringBuffer();
        fileName.append("/data/log/detail/");
        fileName.append(DateTools.getDateDirString());
        fileName.append(DateTools.format(System.currentTimeMillis(), DateConstants.DATE_TIME_SSS_FORMAT));
        fileName.append(" ");
        fileName.append(url.substring(url.indexOf("/") + 2).replaceAll("/","."));
        fileName.append(".log");
        try {
            StringBuilder data = new StringBuilder();
            //请求信息
            data.append("请求时间:\t"+DateTools.format(System.currentTimeMillis(),DateConstants.DATE_TIME_SSS_FORMAT));
            data.append("\n");
            data.append("请求地址:\t"+url);
            data.append("\n");
            data.append("请求IP:\t"+RequestTools.getIP(request));
            data.append("\n");
            data.append("请求方式:\t"+RequestTools.getMethod(request));
            data.append("\n");
            //头信息
            data.append("头信息:\n");
            Set<Map.Entry<String,String>> entries = headers.entrySet();
            for(Map.Entry entry:entries){
                data.append(String.format("%20s : %s\n",entry.getKey(),entry.getValue()));
            }
            //登陆用户信息
            data.append("用户信息:\n");
            if(userSecurityBean == null){
                data.append("无\n");
            }else{
                Map<String,String> userMap = JSONObject.parseObject(userSecurityBean.toJsonString(),HashMap.class);
                Set<Map.Entry<String,String>> userEns = userMap.entrySet();
                for(Map.Entry entry:userEns){
                    data.append(String.format("%20s : %s\n",entry.getKey(),entry.getValue()));
                }
            }
            data.append("\n");
            //传值信息
            data.append("传值:\n");
            Set<Map.Entry<String,String>> paramEntrys = params.entrySet();
            for(Map.Entry entry:paramEntrys){
                data.append(String.format("%20s : %s\n",entry.getKey(),entry.getValue()));
            }
            data.append("\n");
            //返回信息
            data.append("返回:\n"+ modelBean.toJSONString());
            data.append("\n");


            FileTools.write(fileName.toString(), data.toString());
        }catch (Exception e){
            try {
                FileTools.write(fileName.toString(),"记录接口返回数据出错,地址:["+url+"]");
            } catch (IOException e1) {
            }
            logger.error("记录接口返回数据出错,地址:[{}]", url);
            logger.error(e.getMessage(),e.fillInStackTrace());
        }
        long end = System.currentTimeMillis();
//        System.out.println("记录接口详情耗时:" + (end-begin));
    }


    public static void main(String[] args) {
//        Map<String,String> headers = new HashMap<String, String>();
//        headers.put("www","wefwefawef");
//        headers.put("wwswefaefaw","wefweawefaweffawef");
//        Set<Map.Entry<String,String>> entries = headers.entrySet();
//        StringBuffer data = new StringBuffer();
//        for(Map.Entry entry:entries){
//            data.append(String.format("\t%s:%s\n"));
//        }
//        System.out.println("data.toString() = " + data.toString());
//
//
//        String url = "http://ure.zhengzai.tv/m/user/one?userId=5716dfee0cf2cc743b1d48e4";
//        Pattern pat = Pattern.compile(".*/.*");
//        System.out.println("url.replaceAll(\".*/.*\",\".\") = " + url.replaceAll(".*/.*", "."));
//        Matcher mach = pat.matcher(url);
//        if(mach.matches()){
//        }
    }
}
